package edu.qhst.user.controller.front;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.qhst.common.constant.ApiRouterConsts;
import edu.qhst.common.constant.SystemConfigConsts;
import edu.qhst.common.exception.BusinessException;
import edu.qhst.common.req.DeleteReqDto;
import edu.qhst.common.resp.BaseResponse;
import edu.qhst.common.resp.ErrorCode;
import edu.qhst.common.resp.ResultUtils;
import edu.qhst.user.dao.entity.User;
import edu.qhst.user.dto.UserSafeInfoDto;
import edu.qhst.user.dto.req.UserAuditReqDto;
import edu.qhst.user.dto.req.UserLoginReqDto;
import edu.qhst.user.dto.req.UserRegisterReqDto;
import edu.qhst.user.dto.resp.UserLoginRespDto;
import edu.qhst.user.dto.resp.UserRegisterRespDto;
import edu.qhst.user.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 前台门户-用户模块 API 控制器
 *
 * @author 加浓美式
 * @date 2023/6/21
 */
@Tag(name = "FrontUserController", description = "前台-用户模块")
@SecurityRequirement(name = SystemConfigConsts.HTTP_AUTH_HEADER_NAME)
@RestController
@RequestMapping(ApiRouterConsts.API_FRONT_USER_URL_PREFIX)
@RequiredArgsConstructor
@Slf4j
public class FrontUserController {

    private final UserService userService;

    private final RedisTemplate<String, Object> redisTemplate;

    /**
     * 用户注册
     *
     * @param userRegisterRequest 用户注册请求体
     * @return
     */
    @Operation(summary = "申请加入社团")
    @PostMapping("/register")
    public BaseResponse<UserRegisterRespDto> userRegister(@RequestBody UserRegisterReqDto userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String username = userRegisterRequest.getUsername();
        String userClass = userRegisterRequest.getUserClass();
        String phone = userRegisterRequest.getPhone();
        int gender = userRegisterRequest.getGender();
        String email = userRegisterRequest.getEmail();
        if (StringUtils.isAnyBlank(userAccount, username, userClass, phone, email)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数含空");
        }
        UserRegisterRespDto result = userService.userRegister(userAccount, username, userClass, phone, gender, email);
        return ResultUtils.success(result);
    }

    /**
     * 管理员审核
     *
     * @param userAuditRequest
     * @return
     */
    @Operation(summary = "管理员审核")
    @PostMapping("/audit")
    public BaseResponse<Integer> userAudit(@RequestBody UserAuditReqDto userAuditRequest, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "无管理员权限");
        }
        if (userAuditRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int userId = userAuditRequest.getUserId();
        int option = userAuditRequest.getOption();
        String message = userAuditRequest.getMessage();
        int result = userService.userAudit(userId, option, message);
        return ResultUtils.success(result);
    }

    /**
     * 管理员查询待审核的用户
     *
     * @param request
     * @return
     */
    @Operation(summary = "查询待审核的用户")
    @GetMapping("/searchUserByStatus")
    public BaseResponse<List<User>> searchUsersByStatus(HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "无管理员权限");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("userStatus", 1);
        List<User> users = userService.searchUsersByStatus();
        return ResultUtils.success(users);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest 用户登录请求体
     * @param request
     * @return
     */
    @Operation(summary = "登录")
    @PostMapping("/login")
    public BaseResponse<UserLoginRespDto> userLogin(@RequestBody UserLoginReqDto userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.LOGIN_ERROR, "请求参数含空");
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.LOGIN_ERROR, "请求参数含空");
        }
        UserLoginRespDto respDto = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(respDto);
    }

    @Operation(summary = "修改密码")
    @PostMapping("/changePassword")
    public BaseResponse<Boolean> changePassword(@RequestBody String oldPwd, @RequestBody String newPwd, HttpServletRequest request) {
        return ResultUtils.success(userService.changePwd(oldPwd, newPwd, request));
    }


    /**
     * 用户注销,退出登录
     *
     * @param request
     * @return
     */
    @Operation(summary = "退出登录")
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        return ResultUtils.success(userService.userLogout(request));
    }


    /**
     * 获取当前用户信息
     *
     * @param request
     * @return
     */
    @Operation(summary = "查询当前登录用户")
    @GetMapping("/current")
    public BaseResponse<UserSafeInfoDto> getCurrentUser(HttpServletRequest request) {
        return ResultUtils.success(userService.getCurrentUser(request));
    }


    /**
     * 根据姓名查询用户
     *
     * @param username
     * @return
     */
    @Operation(summary = "根据姓名查询用户")
    @GetMapping("/searchByName")
    public BaseResponse<List<UserSafeInfoDto>> searchUserByName(String username, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "无管理员权限");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<UserSafeInfoDto> list = userList.stream()
                .map(userService::getSafetyUser).collect(Collectors.toList());
        return ResultUtils.success(list);
    }


    /**
     * 根据标签查询用户
     *
     * @param tagNameList
     * @return
     */
    @Operation(summary = "根据标签查询用户")
    @GetMapping("/search/tags")
    public BaseResponse<List<UserSafeInfoDto>> searchUsersByTags(@RequestParam(required = false) List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<UserSafeInfoDto> userList = userService.searchUsersByTags(tagNameList);
        return ResultUtils.success(userList);
    }


    /**
     * 删除用户数据
     *
     * @param deleteReqDto
     * @return
     */
    @Operation(summary = "删除用户")
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteReqDto deleteReqDto, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "无管理员权限");
        }
        long id = deleteReqDto.getId();
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户id错误");
        }
        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }


    /**
     * 更新用户信息
     *
     * @param userSafeInfoDto
     * @param request
     * @return
     */
    @Operation(summary = "更新用户")
    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody UserSafeInfoDto userSafeInfoDto, HttpServletRequest request) {
        // 1. 校验参数是否为空
        if (userSafeInfoDto == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserSafeInfoDto loginUser = userService.getCurrentUser(request);
        int result = userService.updateUser(userSafeInfoDto, loginUser);
        return ResultUtils.success(result);
    }


    /**
     * 开发主页（默认推荐和自己兴趣相当的用户）
     *
     * @param pageSize 每页显示条数
     * @param pageNum  当前页
     * @param request
     * @return
     */
    @Operation(summary = "推荐用户")
    @GetMapping("/recommend")
    public BaseResponse<Page<UserSafeInfoDto>> recommendUsers(long pageSize, long pageNum, HttpServletRequest request) {
        return ResultUtils.success(userService.recommendUsers(pageSize, pageNum, request));
    }


    /**
     * 获取最匹配的用户
     *
     * @param num     匹配个数
     * @param request
     * @return
     */
    @Operation(summary = "推荐标签匹配用户")
    @GetMapping("/match")
    public BaseResponse<List<UserSafeInfoDto>> matchUsers(long num, HttpServletRequest request) {
        if (num <= 0 || num > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserSafeInfoDto loginUser = userService.getCurrentUser(request);
        List<UserSafeInfoDto> userList = userService.matchUsers(num, loginUser);
        return ResultUtils.success(userList);
    }

    @Operation(summary = "查看队伍成员ID")
    @GetMapping("/getTeamUsers")
    public BaseResponse<List<Integer>> searchUserIdByTeam(@Parameter(description = "队伍ID") int TeamId) {
        return ResultUtils.success(userService.selectUserIdByTeam(TeamId));
    }

}
